<?php
/**
 * Created by PhpStorm.
 * User: dust2
 * Date: 14-11-21
 * Time: 下午4:28
 */

class Product extends Eloquent
{
    public function classification()
    {
        return $this->belongsTo('Classification', 'class_id', 'id');
    }


    protected static function getProductsByClass($class, $columns = array('*'))
    {
        $data = DB::table('products')
            ->join('classifications', 'products.class_id', '=', 'classifications.id')
            ->where('products.class_id', '=',$class)
            ->select($columns)
            ->limit(10)
            ->get();
        
        return $data;
    }

    public static function getFormatProducts(){
        $columns = [
            'products.class_id', 'products.id',
            'products.name', 'products.image',
            'products.price'
        ];

        $classifications = [];
        $classes = Classification::select(['id', 'label'])->get();

        foreach ($classes as $class) {
            $product = Product::getProductsByClass($class->id,$columns);
            array_push($classifications, [
                'id' => $class->id,
                'label' => $class->label,
                'productList' => $product
            ]);
        }

        return $classifications;
    }

}